package com.stu;

import com.stu.mapper.DataMapper;
import com.stu.po.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Override
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取当前登陆用户信息
        // 获取当前用户
        User user = (User)principals.getPrimaryPrincipal();
        // 获取当前用户名
        String username = user.getUsername();
        // 根据用户名获取角色列表
        List<String> name = DataMapper.getRoleByName(username);
        // 根据用户名获取权限列表
        List<String> permissionList = DataMapper.getPermissionByName(username);
        // 创建授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 添加角色
        info.addRoles(name);
        // 添加权限
        info.addStringPermissions(permissionList);
        // 返回授权信息对象
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //怎么获取数据
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;
        String username =token1.getUsername();
        User user = DataMapper.getUserByName(username);
        if (user == null) {
            return null;
        }
        //SimpleAuthenticationInfo("存入上下文的对象(类似登录成功存入Session中的对象),密码信息,Realm的名字")
//        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        //若进行了加密,我们还需要盐
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
    }
}
